﻿using HPIT.Flat.Data.Entitys;
using Hu.Smart.Core;
using Hu.Smart.Core.Storage;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace Hu.Smart.Application
{
    public class FileController: Controller
    {
        readonly ITempFileCacheManager _tempFileCacheManager;
        public FileController(ITempFileCacheManager tempFileCacheManager)
        {
            _tempFileCacheManager = tempFileCacheManager;
        }

        /// <summary>
        /// 下载生成的excel 文件导出 FileResult
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [AllowAnonymous]
        public IActionResult DownloadTempFile(FileDto file)
        {
            var fileBytes = _tempFileCacheManager.GetFile("CacheName__TempFile" + file.FileToken);
            var FullFileName = System.Web.HttpUtility.UrlDecode(file.FileName, System.Text.Encoding.UTF8);
            return File(fileBytes, file.FileType, FullFileName);
        }

        [AllowAnonymous]
        public IActionResult DownloadTempFilet(string file)
        {
            return Content(DateTime.Now.ToString());
        }

        private string GetCellValue(ExcelWorksheet sheet,int row,int col)
        {
            try
            {
                return sheet.Cells[row, col].Value?.ToString();
            }
            catch (Exception ex)
            {
                return "";
            }
        }
        #region 文件上传 +IActionResult UploadFile()
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <returns></returns>
        [HttpPost("upload")]
        //[DontWrapResult]
        [DisableRequestSizeLimit]
        public async Task<IActionResult> UploadFile(int startrow)
        {
            IFormFileCollection formFiles = HttpContext.Request.Form.Files;
            if (formFiles == null || formFiles.Count == 0)
            {
                return Json(new
                {
                    errno = 1,
                    msg = "请上传文件！"
                });
            }
            List<RoomFeedBack> list = new List<RoomFeedBack>();
            var fileName = ContentDispositionHeaderValue
            .Parse(formFiles[0].ContentDisposition)
            .FileName
            .Trim('"');
            string rootPath = "D:\\ZipPics\\";
            var filePath = Path.Combine(rootPath, formFiles[0].FileName);
            using (var fileStream = new FileStream(filePath, FileMode.Create))
            {
                await formFiles[0].CopyToAsync(fileStream);
            }
            using (FileStream fs = new FileStream(filePath,FileMode.Open))
            {
                ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                using (ExcelPackage package = new ExcelPackage(fs))
                {
                    for (int i = 1; i <= package.Workbook.Worksheets.Count-1; ++i)
                    {
                        ExcelWorksheet sheet = package.Workbook.Worksheets[i];
                        if (sheet.Dimension == null)
                        {
                            continue;
                        }
                        for (int m = startrow, n = sheet.Dimension.End.Row; m <= n; m++)
                        {
                            var model = new RoomFeedBack();
                            model.RoomNo = GetCellValue(sheet,m,1);
                            model.Type = GetCellValue(sheet, m, 2);
                            model.Result = GetCellValue(sheet, m, 3);
                            model.Remark = GetCellValue(sheet, m, 4);
                            list.Add(model);
                        }
                        //for (int j = sheet.Dimension.Start.Column, k = sheet.Dimension.End.Column; j <= k; j++)
                        //{

                        //}
                    }
                }
            }
           
            return Json(new
            {
                Result = list,
                Info="成功"
            });
        }
        #endregion 
    }
}
